<route lang="json5">
  {
    style: {
      "navigationStyle": "custom",
      navigationBarTitleText: '登录',
    },
  }
  </route>

<script lang="ts" setup>
import logo from '@/static/logo.png'
import type { FormInstance } from 'wot-design-uni/components/wd-form/types'
import type { TokenType } from '@/api/login/types'
import { useToast } from 'wot-design-uni'
import * as LoginApi from '@/api/login/index'
import * as authUtil from '@/utils/auth'
import type { LoginFormType } from '@/utils/auth'
import { getPageQueryKeyValue } from '@/utils'
import { useUserStoreWithOut } from '@/store/modules/user'
import { getSafeInfo } from '@/utils/system'
const { success: showSuccess } = useToast()
const userStore = useUserStoreWithOut()

const safeInfo = getSafeInfo()
const pageStyle = computed(() => {
  return {
    paddingTop: `${safeInfo.top}px`,
    boxSizing: 'border-box',
  }
})

const model = reactive<LoginFormType>({
  tenantName: '',
  mobile: '',
  password: '',
  rememberMe: true,
})

const form = ref<FormInstance>()
// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    Object.assign(model, {
      tenantName: loginForm.tenantName
        ? loginForm.tenantName
        : model.tenantName,
      mobile: loginForm.mobile ? loginForm.mobile : model.mobile,
      password: loginForm.password ? loginForm.password : model.password,
      rememberMe: loginForm.rememberMe
        ? loginForm.rememberMe
        : model.rememberMe,
    })
  }
}

function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        showSuccess({
          msg: '校验通过',
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

// 获取租户 ID
async function getTenantId() {
  const res = await LoginApi.getTenantIdByName(model.tenantName)
  authUtil.setTenantId(res)
}
const loading = ref(false)
const handleLogin = async (params: any) => {
  // showSuccess({ msg: authUtil.getAccessToken() })
  loading.value = true
  try {
    await getTenantId()

    form.value!.validate().then(async ({ valid, errors }) => {
      if (valid) {
        const { rememberMe, ...rest } = model
        const loginDataLoginForm = { ...model }
        // loginDataLoginForm.captchaVerification = ''
        try {
          const res = (await LoginApi.login(loginDataLoginForm)) as TokenType
          authUtil.setToken(res)
          await userStore.setUserInfoAction()

          const saveForm = JSON.parse(JSON.stringify(model))
          authUtil.setLoginForm(saveForm)

          let redirect = getPageQueryKeyValue('redirect')
          if (!redirect) {
            redirect = '/pages/index/index'
          }
          uni.switchTab({ url: redirect })
        } finally {
          loading.value = false
        }
        // if (!res) {
        //   return
        // }
        // if (loginDataLoginForm.rememberMe) {
        //   authUtil.setLoginForm(loginDataLoginForm)
        // } else {
        //   authUtil.removeLoginForm()
        // }
        // /pages/index/index
        // await push({ path: redirect.value || permissionStore.addRouters[0].path })
        // uni.switchTab({ url: '/pages/index/index' })
      }
    })
  } finally {
    loading.value = false
  }
}
onLoad(() => {
  getLoginFormCache()
})
</script>

<template>
  <view class="loginPage" :style="pageStyle">
    <view class="my-10px-4 flex flex-col gap-1 mt-20 mb-10 mx-6">
      <view class="flex items-center gap-1">
        <JediImg :width="44" :height="44" :src="logo" mode="aspectFit" custom-style="display: block" />
        <view class="h-11 flex items-center">
          <view class="bg-primary w-fit h-7 rounded-md flex items-center justify-center">
            <i class="iconfont icon-login-text text-6 text-white" />
          </view>
        </view>
      </view>
      <view class="text-title text-2xl"> 数能嘉业师傅版 </view>
    </view>
    <view class="px-6">
      <wd-form ref="form" :model="model">
        <wd-cell-group border>
          <wd-input
            v-model="model.tenantName"
            label-width="100px"
            prop="tenantName"
            clearable
            placeholder="请输入公司名称"
            size="large"
            custom-class="lightBotLine"
            :rules="[{ required: true, message: '请填写公司名称' }]"
          >
            <template #prefix>
              <i class="iconfont icon-company text-lg" />
            </template>
          </wd-input>
          <wd-input
            v-model="model.mobile"
            label-width="100px"
            prop="mobile"
            clearable
            placeholder="请输入手机号"
            size="large"
            custom-class="lightBotLine"
            :rules="[{ required: true, message: '请填写手机号' }]"
          >
            <template #prefix>
              <i class="iconfont icon-cell-phone text-lg" />
            </template>
          </wd-input>
          <wd-input
            v-model="model.password"
            label-width="100px"
            prop="password"
            show-password
            clearable
            placeholder="请输入密码"
            size="large"
            custom-class="lightBotLine"
            :rules="[{ required: true, message: '请填写密码' }]"
          >
            <template #prefix>
              <i class="iconfont icon-password text-lg" />
            </template>
          </wd-input>
        </wd-cell-group>
      </wd-form>
    </view>
    <view class="footer px-6 mt-15">
      <wd-button
        type="primary"
        size="large"
        :loading="loading"
        block
        @click="handleLogin"
      >
        登录
      </wd-button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.loginPage {
}
</style>
